package cn.gzmli.dtt.common.utils;

import com.google.gson.*;
import net.sf.json.JSONObject;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @desc
 * @author MJ~
 * @createtime 2015-11-6 上午11:09:56
 *
 */
public class JsonUtils {
	private static Gson gson = new Gson();

	public static <T> List<T> toBeanList(String json, Class<T[]> clazz){
		T[] array = gson.fromJson(json, clazz);
		return Arrays.asList(array);
	}

	public static <T> T jsonToBean(String json, Class cls) {
		Object t = gson.fromJson(json, cls);
		return (T) t;
	}

	private static <T> List<T> jsonToBeanList(JsonObject jsonObject, String root, Class<T> cls) {
		JsonElement childElement = jsonObject.get(root);
		JsonArray jsonArray = childElement.getAsJsonArray();

		Iterator<JsonElement> iterator = jsonArray.iterator();
		List<T> list = new LinkedList<T>();
		while (iterator.hasNext()) {
			JsonElement jsonElement = iterator.next();
			T t = gson.fromJson(jsonElement, cls);
			list.add(t);
		}
		return list;
	}

	/**
	 *
	 * @param json
	 * @param root
	 *            根据json的指定节点获取解析对象
	 * @param cls
	 * @return 根据指定节点root获取解析后的对象集合
	 */
	public static <T> List<T> jsonToBeanList(String json, String root, Class<T> cls) {
		JsonParser jsonParser = new JsonParser();
		JsonElement jsonElement = jsonParser.parse(json);
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		return jsonToBeanList(jsonObject, root, cls);

	}

	public static String beanToJson(Object object) {
		return gson.toJson(object);
	}

	/**
	 * json字符串转换为map对象
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static Map jsonToObject(String jsonStr) throws Exception {
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		Iterator<String> nameItr = jsonObj.keys();
		String name;
		Map<String, String> outMap = new HashMap<String, String>();
		while (nameItr.hasNext()) {
			name = nameItr.next();
			outMap.put(name, jsonObj.getString(name));
		}
		return outMap;
	}

	public static void main(String[]args){

		try {
			String testStr="INSERT INTO AuditLog (auditerID,workflowID,flowNodeID,formID,status,forworderID,version)"+
					"SELECT u.id,'${workflowID}','${flowNodeID}',${formDataID},0,${forworderID},${version} FROM User u WHERE u.id IN (${userIDSInCond})";
			boolean isExists=Pattern.matches("[\\w\\W]*\\$\\{\\s*version\\s*\\}{1}+[\\w\\W]*",testStr);
			//boolean isExists=testStr.matches("\\'{1}[\\w\\W]+\\'{1}");
			System.out.println(isExists);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
